package org.cloud.ext.mq.strategy;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.cloud.ext.mq.common.MessageTypeEnum;
import org.cloud.ext.mq.common.MqConstants;
import org.cloud.ext.mq.common.PushWayEnum;
import org.cloud.ext.mq.factory.MessageFactory;
import org.cloud.ext.util.res.ApiResult;
import org.cloud.ext.websocket.domain.GroupSession;
import org.cloud.ext.websocket.domain.GroupUser;
import org.cloud.ext.websocket.service.WsService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Set;

/**
 * 报表策略
 * @author xukk
 * @date 2020/3/10
 */
@Service
@Slf4j
public class GroupStrategy implements BaseStrategy, InitializingBean {

    @Autowired
    private SimpUserRegistry userRegistry;
    @Override
    public void handle(JSONObject jsonObject) {
       JSONObject data=jsonObject.getJSONObject(MqConstants.ST.DATA);
       if(null!=data){
           String userCode=data.getString("userCode");
           String group=data.getString("group");
           if(null==group){
               group="";
           }
           group=group.toLowerCase();
           for (PushWayEnum e :PushWayEnum.values()) {
               String uu=e.getCode()+userCode;
               uu=uu.toLowerCase();
               SimpUser simpUser=userRegistry.getUser(uu);
               if(simpUser!=null){
                  String a= GroupUser.getGroup().get(uu);
                  if(!StringUtils.isEmpty(a)&&!a.equalsIgnoreCase(group)){
                      Set set=GroupSession.getGroup().get(a);
                      if(!CollectionUtils.isEmpty(set)){
                          set.remove(uu);
                      }
                  }
                   if(GroupSession.getGroup().containsKey(group)){
                       GroupSession.getGroup().get(group).add(uu);
                   }else {
                       GroupSession.getGroup().put(group, Sets.newConcurrentHashSet());
                   }
                   GroupUser.getGroup().put(uu,group);
               }
           }

       }
        log.warn("此次处理结果：{}",data);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        MessageFactory.register(MessageTypeEnum.GROUP, this);
    }
}
